var express = require('express');
var NodeRSA = require('node-rsa');
var router = express.Router();
// 导入MySQL模块
var mysql = require('mysql');
var pool = mysql.createPool(require('../conf/dbconf'));
//导入uuid
var uuid=require('node-uuid');
//导入二维码模块
var qr_image = require('qr-image');
//加密包
var crypto = require('crypto');
var execSync = require('child_process').execSync;

///////////////////二维码模块///////////////////////////
/**
 * 生成2分钟变化的二维码
 * @returns 二维码png格式图片
 */
let qrcode_time=Date.now();//获取当前时间 
let md5str='';//保存加密串
router.get('/qrcode',function(req,res){
  //时间超过2分钟 
  if(Date.now()- qrcode_time>1000*120){qrcode_time=Date.now();}
  // 加密时间
  md5str=crypto.createHash('md5').update(qrcode_time.toString()).digest('hex');
  res.type('png');  
  qr_image.image(md5str).pipe(res);
});

/**
 * 校验二维码并写入数据库
 * @param
 */
router.post('/received_qrcode',function(req,res){
  //通过cookies获取用户id
  if(req.cookies.username==undefined||req.cookies.username=='') return res.json({msg:'param is empty'});
  //允许迟到时间
  // var later = req.query.later*1000*60;
  var later=20*1000*60;
  // //获取上课时间
  // var begintime = new Date().toLocaleDateString()+" "+req.query.classbegin;
  var begintime = new Date().toLocaleDateString()+' '+new Date().toLocaleTimeString();
  var btnumber = new Date(begintime).getTime();
  // //获取上课节次
  // var classnode = req.query.classnode;
  var classnode = 1;
  console.log('时间:'+new Date(begintime).getTime()+" 现在时间："+Date.now()+" 延迟时间:"+(btnumber+later));
  console.log("later:"+later+" begintime:"+begintime+" classnode:"+classnode);
  //获取签到用户
  var userid = req.cookies.username;
  //校验二维码begintime
  // var qrcode = req.query.qrcode;
  var qrcode =req.body.up_date;
  //判断是否在上课前
  var state;
  if(btnumber>Date.now() && md5str==qrcode){
    //在上课时间前
    state=1;
    }else if(btnumber<Date.now() && (btnumber+later)>Date.now() && md5str==qrcode){
      // 迟到20分钟内
      state=0;
    }else{
      //无签到
      state=-1;
      return res.json({status:state});
  }
// 写记录到数据库
  pool.getConnection(function(err,connection){
    if(err) throw err;
    var args=[uuid.v1(),userid,classnode,new Date().toLocaleDateString(),state,"未知课程代码"];
    connection.query("insert into sign_in values(?,?,?,?,?,?)",args,function(err,results){
      if(err) throw err;
      if(results.affectedRows>0) res.json({status:state});
    });
    connection.release();
  });
});

// 获取个人考勤记录
router.get('/listPersonRecord',(req,res)=>{
  var userid= req.query.id;
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    var sql='SELECT u.username,s.node,s.time,s.state FROM sign_in AS s LEFT JOIN `user` AS u ON(s.userid=u.uid) WHERE s.userid=?';
    connection.query(sql,userid,(err,results)=>{
      if(err) throw err;
      res.json(results);
    });
    connection.release();
  });
});
/////////////////////////////数据录入部分/////////////////////
// 自动录入数据服务端接口
router.get('/autodata',(req,res)=>{
  // 校验数据是否为空
  if(req.query.data==undefined) {return res.json({msg:'data is empty'});}
  let data=JSON.parse(req.query.data);
  let app_his_id=uuid.v1();
  data.autoData['app_his_id']=app_his_id;
  // 拼接插入app_his的sql语句
  let insertapp_hisSql='insert into app_his values';
  data.list.forEach(element => {insertapp_hisSql+='("'+app_his_id+'","'+element.appName+'",'+element.useTime+'),';});
  insertapp_hisSql=insertapp_hisSql.substr(0,insertapp_hisSql.length-1);
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    connection.query('SELECT app_his_id FROM `autodata` WHERE date=? AND userid=?',[data.autoData.date,req.cookies.username],(err,results)=>{
      if(err) throw err;
      // 判断是否有昨日数据
      if(results.length==0){
        connection.query('INSERT INTO autodata set ?',data.autoData,(err,results)=>{
          if(err) throw err;
          if (results.affectedRows>0) {
            // 使用app使用历史记录
            connection.query(insertapp_hisSql,(err,results)=>{
              if(err) throw err;
              if (results.affectedRows>0)res.json({msg:'1',note:'insert app_his success'});
            });
          }else{
            res.json({msg:'0'});
          }
        });
      }else{
        res.json({msg:'-1'});
      }
    });
    connection.release();
  });
});
//GPS定位数据
router.get('/addLocation',(req,res)=>{
  // 校验数据是否为空
  if(req.query.data==undefined||req.query.data=='null') return res.json({msg:'data is empty'});
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    connection.query('insert into gps set ?',JSON.parse(req.query.data),(err,results)=>{
      if(err) throw err;
      if(results.affectedRows>0) res.json({code:'200',msg:results})
      else res.json({msg:results});
    });
    connection.release();
  });
});
// 录入课程评分
router.get('/addCourseScore',function(req,res){
  // 评分数组
  if(req.query.score==undefined||req.query.score=='') return res.json({msg:'data is empty'});
  var score=req.query.score;
  // 用户id
  if(req.query.userid==undefined||req.query.userid=='') return res.json({msg:'data is empty'});
  var userid=req.session.userid;
  // 总成绩(字符数组转数字字符对象)
  var allscore=JSON.parse('['+score+']');
  var sum=0;
  allscore.forEach(element => {
    sum+=element;
  });
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    connection.query('INSERT INTO course_score VALUES(?,?,?,?)',[uuid.v1(),userid,score.join(','),sum],(err,results)=>{
      if(err) throw err;
      if(results.affectedRows>0){
        res.json({'msg':1});
      }else{
        res.json({'msg':0});
      }
    });
    connection.release();
  });
});
/**
 * 查询雷达图所需的数字以及拼接成功的提示
 */
router.get('/ldt',function(req,res){
  //1.获取session中的用户id
  var sid = req.session.userid;
  
  pool.getConnection((err,connection)=>{
    if(err) return err;
    var sj_arr = [];

  //2.根据sid获取qqnum，根据qqnum去python解析表(lol_radar)查找数据并加工，写入sj_lol
    connection.query("select * from lol_radar where qqnum in (select qqnum from bind_lol where stu_id=?)",[sid],(err,result)=>{
      if(err) throw err;
      console.log(result);
      //加工数据(输出，发育，团战，生存，防御)
      
      sch = result[0].magic*50+result[0].physic*50;
      fy = result[0].money*100;
      tz = result[0].assists*100;
      sc=result[0].existence*100;
      kda=result[0].defense*100;
      
      sj_arr[0]=sch;sj_arr[1]=fy;sj_arr[2]=tz;sj_arr[3]=sc;sj_arr[4]=kda;
  //3.查找五条数据的词条
  var desc = "";
  //遍历数组,根据值判断匹配的输出语句
  sj_arr.forEach(function(v,i,a){
    //如果值在1-30，就是第一档次，后面每5个分值为一个档次
    if(v-30<=0){
      var num = 1;
    }else{
      var num = Math.ceil((v-30)/5)+1;
    }
    //拼接查找的参数

    if(num<=9){
      var numb = '00'+(i+1)+'00'+num;
    }else{
      var numb = '00'+(i+1)+'0'+num;
    }
    
    //查找对应的文字说明
    connection.query('select dict_memo from base_dict where dict_item_code=?',[numb],(err,results)=>{
      if(i!=4){
        desc+=results[0].dict_memo+",";
      }else{
        desc+=results[0].dict_memo;
        res.json({'data':sj_arr,'desc':desc});
      }

    });

  });

    });

    /**
     * //sj_lol查询加工后的五条数据
    connection.query('select name,value from sj_lol where stu_id=?',[sid],(err,results)=>{
      
      //这种一次查询五条的方式，避免会有顺序错乱，因此重新组装数据到数组中
     
      results.forEach(function(v,i,a){
        nl_name = v.name;

        switch (nl_name) {
          case "sch":
            sj_arr[0]=v.value;
            break;
          case "fy":
            sj_arr[1]=v.value;
          case "tz":
            sj_arr[2]=v.value;
          case "sc":
            sj_arr[3]=v.value;
          case "kda":
            sj_arr[4]=v.value;
        }
        
      });
      
      var desc = "";
      //遍历数组,根据值判断匹配的输出语句
      sj_arr.forEach(function(v,i,a){
        //如果值在1-30，就是第一档次，后面每5个分值为一个档次
        if(v-30<=0){
          var num = 1;
        }else{
          var num = Math.ceil((v-30)/5)+1;
        }
        //拼接查找的参数

        if(num<=9){
          var numb = '00'+(i+1)+'00'+num;
        }else{
          var numb = '00'+(i+1)+'0'+num;
        }
        console.log(num);
        console.log(numb);
        //查找对应的文字说明
        connection.query('select dict_memo from base_dict where dict_item_code=?',[numb],(err,results)=>{
          if(i!=4){
            desc+=results[0].dict_memo+",";
          }else{
            desc+=results[0].dict_memo;
            res.json({'data':sj_arr,'desc':desc});
          }

        });

      });
    });
     */
    connection.release();
  });
});

/**
 * 用户请求查看自己的能力图
 */
router.get('/searchnl',function(req,res){
  var sid = req.session.userid;
  //将该请求记录到数据库
  pool.getConnection((err,connection)=>{
    if(err) return err;
    connection.query("insert into req_lol(id,stu_id) values(?,?)",[uuid.v1(),sid],(err,results)=>{
      if(err) throw err;
      console.log("申请查看成功!");
    });
    connection.release();
  });
});
module.exports = router;

